#include <windows.h>		// Header File For Windows
#include "level.h"
#include "renderer.h"
#include "camera.h"
#include "character.h"
#include "game.h"
#include "defines.h"
#include "io.h"
#include "hunter.h"
#include "zomby.h"
#include "kolobok.h"
#include "audio.h"

#include "point2.h"
#include "rect.h"
#include "source.h"
#include "globals.h"
#include "input.h"
#include "platform.h"	//? n oneed in the future
#include "resource.h"

#define STATE_MENU 1
#define STATE_GAMEON 2
#define STATE_EXIT 3

HDC			hDC=NULL;		// Private GDI Device Context
HGLRC		hRC=NULL;		// Permanent Rendering Context
HWND		hWnd=NULL;		// Holds Our Window Handle
HINSTANCE	hInstance;		// Holds The Instance Of The Application

bool	active=TRUE;		// Window Active Flag Set To TRUE By Default
bool	fullscreen=TRUE;	// Fullscreen Flag Set To Fullscreen Mode By Default
bool	pause;
bool	cursor;
int		game_state;
//bool	start_game =false;
int		game_mode;
int		mouseX =0;
int		mouseY =0;
unsigned int extra =0;
DEVMODE	old_resolution;
DEVMODE new_resolution;
int speed =100;


Level*	cur_level =NULL;
Camera*	cam =NULL;
Character*	player =NULL;

LRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);	// Declaration For WndProc
void drawFPS(int fps);
void menuFunc(MSG& msg);
void gameFunc(MSG& msg, mrKeyboard* kbd);

void clearData(){

	delete cur_level;
	cur_level =NULL;
	delete cam;
	cam =NULL;
	delete player;
	player =NULL;

	clearIO();
}

int loadData(){

	Audio* audio =Audio::Instance();

	cur_level =loadLevel("level.txt", true);
	if(!cur_level){

		clearData();
		return -1;
	}
	player =loadHunter("player.txt", true);
//player =loadZomby("zomby1.txt", true);
//	player =loadKolobok("kolobok.txt");
	if(!player){

		clearData();
		return -1;
	}
//	player->setState(STATE_STILL, AIM_STRAIGHT);
	player->setStill(AIM_STRAIGHT);
	player->position->x =cur_level->player_position_x;
	player->position->y =cur_level->player_position_y;
	player->layer =cur_level->player_layer;
	player->orientation->x =-1;
	player->orientation->y =0;

	// create camera
	cam =loadCamera("camera.txt");
	cam->rect =new Rect;
	cam->eye =new Point2;
	// normal
	cam->rect->xLo =player->position->x -cam->width/2;
	cam->eye->x =player->position->x;
	// camera if out of lower edge
	if(cur_level->rect->xLo > player->position->x -cam->width/2){
		cam->rect->xLo =cur_level->rect->xLo;
		cam->rect->xHi =cam->rect->xLo +cam->width;

//		cam->eye->x =player->position->x;
	}
	// camera if out of higer edge
	else if(cur_level->rect->xHi < player->position->x +cam->width/2){
		cam->rect->xHi =cur_level->rect->xHi;
		cam->rect->xLo =cam->rect->xHi -cam->width;
	}
	cam->rect->xHi =cam->rect->xLo +cam->width;

	cam->rect->yLo =player->position->y -cam->height/2;
	cam->eye->y =player->position->y;
	if(cur_level->rect->yLo > player->position->y -cam->height/2){
		cam->rect->yLo =cur_level->rect->yLo;
		cam->rect->yHi =cam->rect->yLo +cam->height;
	}
	else if(cur_level->rect->yHi < player->position->y +cam->height/2){
		cam->rect->yHi =cur_level->rect->yHi;
		cam->rect->yLo =cam->rect->yHi -cam->height;
	}
	cam->rect->yHi =cam->rect->yLo +cam->height;

	list<Source*>::iterator iter_source;
	for(iter_source = cur_level->sources.begin(); iter_source != cur_level->sources.end(); iter_source++)
	{
		audio->playSource((*iter_source)->id);
	}

	audio->SetListener(player->position->x, player->position->y, 0, 0);		

	return 0;
}

void killGLWindow()									// Properly Kill The Window
{
	if (fullscreen)										// Are We In Fullscreen Mode?
	{
		ChangeDisplaySettings(NULL,0);					// If So Switch Back To The Desktop
		while(ShowCursor(TRUE)<0);						// show cursor
	}

	if (hRC)											// Do We Have A Rendering Context?
	{
		if (!wglMakeCurrent(NULL,NULL))					// Are We Able To Release The DC And RC Contexts?
		{
			MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}

		if (!wglDeleteContext(hRC))						// Are We Able To Delete The RC?
		{
			MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		hRC=NULL;										// Set RC To NULL
	}

	if (hDC && !ReleaseDC(hWnd,hDC))					// Are We Able To Release The DC
	{
		MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hDC=NULL;										// Set DC To NULL
	}

	if (hWnd && !DestroyWindow(hWnd))					// Are We Able To Destroy The Window?
	{
		MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hWnd=NULL;										// Set hWnd To NULL
	}

	if (!UnregisterClass("OpenGL",hInstance))			// Are We Able To Unregister Class
	{
		MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hInstance=NULL;									// Set hInstance To NULL
	}
}

/*	This Code Creates Our OpenGL Window.  Parameters Are:					*
 *	title			- Title To Appear At The Top Of The Window				*
 *	width			- Width Of The GL Window Or Fullscreen Mode				*
 *	height			- Height Of The GL Window Or Fullscreen Mode			*
 *	bits			- Number Of Bits To Use For Color (8/16/24/32)			*
 *	fullscreenflag	- Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE)	*/
 
BOOL createGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
	unsigned int	PixelFormat;			// Holds The Results After Searching For A Match
	WNDCLASS	wc;						// Windows Class Structure
	DWORD		dwExStyle;				// Window Extended Style
	DWORD		dwStyle;				// Window Style
	RECT		WindowRect;				// Grabs Rectangle Upper Left / Lower Right Values

	WindowRect.left=(long)0;			// Set Left Value To 0
	WindowRect.right=(long)width;		// Set Right Value To Requested Width
	WindowRect.top=(long)0;				// Set Top Value To 0
	WindowRect.bottom=(long)height;		// Set Bottom Value To Requested Height

	fullscreen=fullscreenflag;			// Set The Global Fullscreen Flag

	hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window
	wc.style			= CS_NOCLOSE | CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.
	wc.lpfnWndProc		= (WNDPROC) WndProc;					// WndProc Handles Messages
	wc.cbClsExtra		= 0;									// No Extra Window Data
	wc.cbWndExtra		= 0;									// No Extra Window Data
	wc.hInstance		= hInstance;							// Set The Instance
	wc.hIcon			= LoadIcon(NULL, IDI_WINLOGO);			// Load The Default Icon
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);			// Load The Arrow Pointer
	wc.hbrBackground	= NULL;									// No Background Required For GL
	wc.lpszMenuName		= NULL;									// We Don't Want A Menu
	wc.lpszClassName	= "OpenGL";								// Set The Class Name

	if (!RegisterClass(&wc))									// Attempt To Register The Window Class
	{
		MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;											// Return FALSE
	}

	dwStyle =0;
//	dwStyle =WS_OVERLAPPEDWINDOW | WS_DLGFRAME;
//	dwStyle =dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;

	if (fullscreen)												// Are We Still In Fullscreen Mode?
	{
		dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style
		dwStyle =dwStyle | WS_POPUP;										// Windows Style
		while(ShowCursor(FALSE)>=0);			// hide cursor
	}
	else
	{
		dwStyle =dwStyle | WS_CAPTION;
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style
		int res;
		res =AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size
	}

	// Create The Window
	if (!(hWnd=CreateWindowEx(	dwExStyle,							// Extended Style For The Window
								"OpenGL",							// Class Name
								title,								// Window Title
								dwStyle,					
								0, 0,								// Window Position
								WindowRect.right-WindowRect.left,	// Calculate Window Width
								WindowRect.bottom-WindowRect.top,	// Calculate Window Height
								NULL,								// No Parent Window
								NULL,								// No Menu
								hInstance,							// Instance
								NULL)))								// Dont Pass Anything To WM_CREATE
	{
		killGLWindow();								// Reset The Display
		MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(hDC=GetDC(hWnd)))							// Did We Get A Device Context?
	{
		killGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		3,											// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		0,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};

//	if(pfd.dwFlags&PFD_GENERIC_ACCELERATED)
//	{
//		killGLWindow();								// Reset The Display
//		MessageBox(NULL,"Format Is Not Hardware Accelerated.","ERROR",MB_OK|MB_ICONEXCLAMATION);
//		return FALSE;								// Return FALSE
//	}

	if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))	// Did Windows Find A Matching Pixel Format?
	{
		killGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!SetPixelFormat(hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?
	{
		killGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(hRC=wglCreateContext(hDC)))				// Are We Able To Get A Rendering Context?
	{
		killGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!wglMakeCurrent(hDC,hRC))					// Try To Activate The Rendering Context
	{
		killGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	ShowWindow(hWnd,SW_SHOW);						// Show The Window
	SetForegroundWindow(hWnd);						// Slightly Higher Priority
	SetFocus(hWnd);									// Sets Keyboard Focus To The Window

	return TRUE;									// Success
}

LRESULT CALLBACK WndProc(	HWND	hWnd,			// Handle For This Window
							UINT	uMsg,			// Message For This Window
							WPARAM	wParam,			// Additional Message Information
							LPARAM	lParam)			// Additional Message Information
{
	Renderer* renderer =Renderer::Instance();
	Game* game =Game::Instance();

	switch (uMsg)									// Check For Windows Messages
	{
		case WM_ACTIVATE:							// Watch For Window Activate Message
		{
			if (!HIWORD(wParam))					// Check Minimization State
			{
				active=TRUE;						// Program Is Active
			}
			else
			{
				active=FALSE;						// Program Is No Longer Active
			}

			return 0;								// Return To The Message Loop
		}

		case WM_SYSCOMMAND:							// Intercept System Commands
		{
			switch (wParam)							// Check System Calls
			{
				case SC_SCREENSAVE:					// Screensaver Trying To Start?
				case SC_MONITORPOWER:				// Monitor Trying To Enter Powersave?
				return 0;							// Prevent From Happening
			}
			break;									// Exit
		}

		case WM_CLOSE:								// Did We Receive A Close Message?
		{
			PostQuitMessage(0);						// Send A Quit Message
			return 0;								// Jump Back
		}
		
		case WM_LBUTTONDOWN:
		{
			if(game_mode ==STATE_MENU){
				if(renderer->select(mouseX, mouseY, renderer->btnStart)>0){
					game_mode =STATE_GAMEON;
				}
				else
				if(renderer->select(mouseX, mouseY, renderer->btnExit)>0){
					game_mode =STATE_EXIT;
				}
			}

			break;
		}

		case WM_MOUSEMOVE:
		{
			if(game_mode==STATE_MENU){
				mouseX =LOWORD(lParam);
				mouseY = HIWORD(lParam);
//				if(!fullscreen)
//					mouseY +=GetSystemMetrics(SM_CYCAPTION);
				mouseX =800 -mouseX*(800.0f/(float)new_resolution.dmPelsWidth); 
				mouseY =600 -mouseY*(600.0f/(float)new_resolution.dmPelsHeight); 
			}
			break;
		}

		case WM_KEYDOWN:							// Is A Key Being Held Down?
		{
			game->keys[wParam] = TRUE;					// If So, Mark It As TRUE

//			if(game_mode!=STATE_GAMEON)
//				break;

			switch(wParam){
			case 'X':
				game->keys['X'] =false;
				extra =extra^renderer->DRAW_GEOMETRY;
				break;
			case 'P':
				game->keys['P'] =false;
				pause =!pause;
				break;
			case 'G':
				game->keys['G'] =false;
				extra =extra^renderer->DRAW_GRID;
				break;
			case 'A':
				game->keys['A'] =false;
				extra =extra^renderer->DRAW_AXIS;
				break;
			case 'C':
				game->keys['C'] =false;
				extra =extra^renderer->DRAW_CAMERA;
				break;
			case 'I':
				game->keys['I'] =false;
				extra =extra^renderer->DRAW_INFO;
				break;
			case 'K':	//?
				ShowCursor(FALSE);
				break;
			case 'L':
				ShowCursor(TRUE);
				break;
			case 'Q':
				game->keys['Q'] =false;
				game_mode =STATE_MENU;
				break;
			case VK_ADD:
				game->keys[VK_ADD] =false;
//				if(speed<2.0f)
				//speed +=1;
				LOGIC_CYCLE_TIME +=1;
				break;
			case VK_SUBTRACT:
				game->keys[VK_SUBTRACT] =false;
				//if(speed>1)
				//	speed -=1;
				if(LOGIC_CYCLE_TIME>1)
					LOGIC_CYCLE_TIME -=1;
				break;
			}

			return 0;								// Jump Back
		}

		case WM_KEYUP:								// Has A Key Been Released?
		{
			game->keys[wParam] = FALSE;					// If So, Mark It As FALSE
			if(wParam==VK_SHIFT)
				game->jump_ready =true;
			return 0;								// Jump Back
		}

		case WM_SIZE:								// Resize The OpenGL Window
		{
			// LoWord=Width, HiWord=Height
			renderer->reSizeGLScene(new_resolution.dmPelsWidth ,new_resolution.dmPelsHeight);
			return 0;								// Jump Back
		}
	}

	// Pass All Unhandled Messages To DefWindowProc
	return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

/* Config Dialog Box *********************************************************************************************/
LRESULT CALLBACK ConfigDlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	Game* game =Game::Instance();
	switch (msg)
	{
		case WM_INITDIALOG:
		{
			char temp[500];

			EnumDisplaySettings (NULL, ENUM_CURRENT_SETTINGS, &old_resolution);			

			sprintf (temp, "640x480");
			SendDlgItemMessage (hWnd, IDC_RESOLUTION, CB_ADDSTRING, 0, (LPARAM)temp);
			sprintf (temp, "800x600");
			SendDlgItemMessage (hWnd, IDC_RESOLUTION, CB_ADDSTRING, 0, (LPARAM)temp);
			sprintf (temp, "1024x768");
			SendDlgItemMessage (hWnd, IDC_RESOLUTION, CB_ADDSTRING, 0, (LPARAM)temp);

			SendDlgItemMessage (hWnd, IDC_RESOLUTION, CB_SETCURSEL, 0, 1);			
		} break;
		case WM_COMMAND:
		{
			if (wParam == IDEXIT) EndDialog (hWnd, 0);
			else if (wParam == IDOK) 
			{				
				long	cursel = SendDlgItemMessage (hWnd, IDC_RESOLUTION, CB_GETCURSEL, 0, 0);
				new_resolution = old_resolution;

				switch(cursel){
				case CB_ERR:
					EndDialog (hWnd, -1);
					break;
				case 0:
					new_resolution.dmPelsWidth =640;
					new_resolution.dmPelsHeight =480;
					break;
				case 1:
					new_resolution.dmPelsWidth =800;
					new_resolution.dmPelsHeight =600;
					break;
				case 2:
					new_resolution.dmPelsWidth =1024;
					new_resolution.dmPelsHeight =768;
					break;
				default:
					EndDialog (hWnd, -2);
					break;
				}

				if (SendDlgItemMessage (hWnd, IDC_CHECK_FULL, BM_GETCHECK, 0, 0) == BST_CHECKED) 
					fullscreen = true;
				else fullscreen = false;

				if (SendDlgItemMessage (hWnd, IDC_CHECK_SND, BM_GETCHECK, 0, 0) == BST_CHECKED) 
					game->sound = false;
				else game->sound = true;

				if(fullscreen)
					ChangeDisplaySettings (&new_resolution, 0);

				EndDialog (hWnd, 1);
			}
		} break;
	}
	return (0);
}

int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	Renderer* renderer =Renderer::Instance();
	Game* game =Game::Instance();
	Audio* audio =Audio::Instance();
	MSG		msg;									// Windows Message Structure
	pause =false;
	int res =0;

//	timeBeginPeriod(1);	//?
	res =DialogBox (hInstance, MAKEINTRESOURCE(IDD_CONFIG), NULL, (DLGPROC)ConfigDlgProc);
	switch(res)
	{
	case 0:
		return (0);
	case -1:
		MessageBox (NULL, "No resolution selected", NULL, MB_OK);
		return (0);
	case -2:
		MessageBox (NULL, "Wrong resolution selected (BUG)", NULL, MB_OK);
		return (0);
	}

	// Create Our OpenGL Window
	if (!createGLWindow("KASHALOT",new_resolution.dmPelsWidth,new_resolution.dmPelsHeight,32,fullscreen))
	{
		return 0;									// Quit If Window Was Not Created
	}

	// Set Up Our Perspective GL Screen
	renderer->reSizeGLScene(new_resolution.dmPelsWidth, new_resolution.dmPelsHeight);

	if(loadConfig("config.txt")<0){

		MessageBox(NULL,"Error loading 'config.txt'.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return -1;
	}

	mrInputManager m_kInputManager;
	mrKeyboard m_kKeyboard;

//	if(!m_kInputManager.Init(hInstance))
//		return 0;
//	if(!m_kKeyboard.Init(hWnd))
//		return 0;

	if(game->sound){
		if (!audio->Init()) 
			audio->Release();
	}

	if (!renderer->initGL())									// Initialize Our Newly Created GL Window
	{
		killGLWindow();								// Reset The Display
		MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!initGlobals()){

		MessageBox(NULL,"Error initializing globals.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}
	game_mode =STATE_MENU;
//	game_mode =STATE_GAMEON;
	while(game_mode!=STATE_EXIT){

		switch(game_mode){

		case STATE_MENU:
			menuFunc(msg);
			break;
		case STATE_GAMEON:
			gameFunc(msg, &m_kKeyboard);
			break;
		}
	}

	releaseGlobals();
	audio->Release();
	renderer->releaseGL();
	delete renderer;
	killGLWindow();									// Kill The Window
	if(fullscreen)
		ChangeDisplaySettings (&old_resolution, 0);
	return (msg.wParam);							// Exit The Program
}

void menuFunc(MSG& msg){

	Renderer* renderer =Renderer::Instance();

	loadMenu();										// load menu data
	while(game_mode==STATE_MENU){

		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				game_mode =STATE_EXIT;
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
			continue;
		}

		renderer->drawMenu();
		renderer->drawCross(20, 20, mouseX, mouseY);
		SwapBuffers(hDC);
	}
	releaseMenu();
}

// timing, game cycle and rendering - all happens here
void gameFunc(MSG& msg, mrKeyboard* kbd){

	Renderer* renderer =Renderer::Instance();
	Game* game =Game::Instance();
	assert(renderer);
	DWORD fps_time, t1, t2, dt, cycle_time;
	int ctr_cycle_time, ctr_fps, FPS, lms, CYCLE_TIME, cycle_time_total;
	
	game->scores =0;
	while(game_mode==STATE_GAMEON){			// 
		// initialize game
		if(loadData()<0){

			clearData();
			MessageBox(NULL,"error loading data", "ERROR", MB_ICONERROR);
			game_mode =STATE_EXIT;
			return;
		}
		// game's "main loop"
		ctr_fps =0;
		FPS =60;//?	desired FPS
		fps_time =timeGetTime();
		t1 =timeGetTime();

		CYCLE_TIME =0;
		cycle_time_total =0;
		cycle_time =timeGetTime();
		ctr_cycle_time =0;

		game_state =GAME_ON;
		while(game_mode==STATE_GAMEON)
		{
			if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
				continue;
			}
			if (game->keys[VK_ESCAPE])
			{
				game->keys[VK_ESCAPE] =false;
				if(game_state!=GAME_WON && game_state!=GAME_LOST){
					game_mode =STATE_GAMEON;
					break;
				}
			}
			if(game->keys['Y'])
			{
				game->keys[VK_ESCAPE] =false;
				if(game_state==GAME_WON || game_state==GAME_LOST){
					game_mode =STATE_GAMEON;
					game_state =GAME_ON;
					break;
				}
			}
			if(game->keys['N'])
			{
				game->keys[VK_ESCAPE] =false;
				if(game_state==GAME_WON || game_state==GAME_LOST){
					game_mode =STATE_MENU;
					break;
				}
			}

			t2 =timeGetTime();
			dt =t2-t1;
			t1 =timeGetTime();

			lms =timeGetTime();
			if(!pause && game_state==GAME_ON){
				game->processKeys(cur_level, player, kbd);
				// udjust LOGIC_CYCLE_TIME for high FPS
//				if(FPS==0)
//					FPS=1;
//				LOGIC_CYCLE_TIME =(15*60)/((float)FPS);
//				if(LOGIC_CYCLE_TIME>5)		//? hardcoded
//				LOGIC_CYCLE_TIME =MAX_LOGIC_CYCLE_TIME;

				// if frame time (lms + rendering) < 1ms make it 1ms, otherwise the game will stuck
				if(dt==0)
					dt=1;
				game_state =game->runGameLogic(cur_level, player, cam, (float)dt*(float)speed/100.0f);
			}
			lms =timeGetTime() -lms;

			renderer->renderGLScene(cur_level, player, cam, extra);

			// draw overlay (HUD)
			renderer->beginOverlay(640, 480);
			if(game_state==GAME_WON)
				renderer->drawWon();
			else if(game_state==GAME_LOST)
				renderer->drawLost();
			else if(pause)
				renderer->drawPause();

			if(extra&renderer->DRAW_INFO){
				renderer->drawPerformance(FPS, lms, speed, CYCLE_TIME);
				renderer->drawInfo(player);
				renderer->drawLevelInfo(cur_level);
			}
			renderer->endOverlay();

			SwapBuffers(hDC);					// Swap Buffers (Double Buffering)

			// update FPS
			ctr_fps++;
			if(timeGetTime()-fps_time >= 200)
			{
				FPS =(ctr_fps*1000)/(timeGetTime()-fps_time);
				ctr_fps =0;
				fps_time =timeGetTime();
			}

			// update CYCLE_TIME
			ctr_cycle_time++;
			cycle_time_total +=game->cycle_time;
			if(timeGetTime()-cycle_time >= 10000) //? constant
			{
				CYCLE_TIME =static_cast<int>(static_cast<float>(cycle_time_total)/static_cast<float>(ctr_cycle_time));

				ctr_cycle_time =0;
				cycle_time_total =0;
				cycle_time =timeGetTime();
			}
		}

		clearData();
	}

	game_mode =STATE_MENU;
}